package com.fenrirtec.aepp.common.support;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.SessionAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.definition.CommonDefinition;
import com.fenrirtec.aepp.common.dto.MemberDto;
import com.fenrirtec.aepp.common.dto.SystemConfigDto;
import com.fenrirtec.aepp.common.dto.UserDto;
import com.fenrirtec.aepp.common.service.impl.SystemConfigServiceImpl;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.support.BaseActionSupport;

public abstract class JSONActionSupport extends BaseActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private static SystemConfigDto mSystemConfig = null;
	
	private UserDto mUserInfo;
	
	private MemberDto mMemberInfo;
	
	private Map<String, Object> mSession = null;
	
	private static final Logger logger = LoggerFactory.getLogger(JSONActionSupport.class);

	public SystemConfigDto getSystemConfig() {
		return mSystemConfig;
	}
	
	public void setSystemConfig(SystemConfigDto systemConfigDto) {
		mSystemConfig = systemConfigDto;
	}
	
	public UserDto getUserInfo() {
		return mUserInfo;
	}
	
	public MemberDto getMemberInfo() {
		return mMemberInfo;
	}

	protected JSONActionSupport() {
		if (mSystemConfig == null) {
			try {
				mSystemConfig = new SystemConfigServiceImpl().loadSystemConfig();
			} catch (DatabaseException e) {
				if (logger.isErrorEnabled()) {
					logger.error("[JSONActionSupport#JSONActionSupport] database error occurred.", e);
				}
				throw e;
			} catch (UnexpectedException e) {
				if (logger.isErrorEnabled()) {
					logger.error("[JSONActionSupport#JSONActionSupport] unexpected error occurred.", e);
				}
				throw e;
			} finally {
				if (logger.isInfoEnabled()) {
					logger.info("[JSONActionSupport#JSONActionSupport] finish.");
				}
			}
		}
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.mSession = session;
		if (mUserInfo == null || StringUtils.isEmpty(mUserInfo.getLoginName())) {
			mUserInfo = (UserDto) getSession().get(CommonDefinition.SessionKey.USER_INFO);
		}
		if (mMemberInfo == null || StringUtils.isEmpty(mMemberInfo.getMemberLoginName())) {
			mMemberInfo = (MemberDto) getSession().get(CommonDefinition.SessionKey.MEMBER_INFO);
		}
	}

	public Map<String, Object> getSession() {
		return this.mSession;
	}
}
